import React, { useState, useEffect } from 'react';
import _ from 'lodash';
import { nanoid } from 'nanoid';
import { Drawer, Empty, Spin } from 'antd';
import { fetchJobListWithDepartmentRelation } from '@/services/system/department';
import styles from './jobRelationDrawer.less';

export default ({ visible, departmentId, closeDrawer }) => {
  const [jobList, setJobList] = useState([]);
  const [listLoadingId, setListLoadingId] = useState('');

  // 获取机构关联的岗位列表
  const getJobRelationList = async (organId) => {
    try {
      const res = await fetchJobListWithDepartmentRelation({ organId });
      return _.isArray(res) ? _.filter(res, (item) => _.isPlainObject(item)) : [];
    } catch (e) {
      return [];
    }
  };

  // 初始化
  useEffect(() => {
    if (visible) {
      const nextListLoadingId = nanoid(12);
      setListLoadingId(nextListLoadingId);
      getJobRelationList(departmentId).then((list) => {
        let validDataFetch;
        setListLoadingId((currentId) => {
          if (currentId === nextListLoadingId) {
            validDataFetch = true;
            return '';
          }
          return currentId;
        });
        if (validDataFetch) {
          console.log(list);
          setJobList(list);
        }
      });
      return;
    }
    setJobList([]);
    setListLoadingId('');
  }, [visible]);

  return (
    <Drawer visible={visible} title={'已关联的岗位'} onClose={closeDrawer}>
      <Spin spinning={!!listLoadingId} tip="加载中...">
        {jobList.length ? (
          <ul className={styles.jobListContainer}>
            {jobList.map((item, index) => (
              <li key={`${item.id}-${index}`} className={styles.jobListItem}>
                {item.postName || ''}
                {item.postStatus !== '1' && <span className={styles.disabledRole}>[禁用]</span>}
              </li>
            ))}
          </ul>
        ) : (
          <Empty description={'暂无数据'} />
        )}
      </Spin>
    </Drawer>
  );
};
